<script setup>
import { ref, defineExpose } from "vue";
import {
  artAddChannelService,
  artEditChannelService,
} from "@/api/other/article";
import { defineEmits } from "vue";

// 弹窗
let dialogVisible = ref(false);

// 表单ref
const ruleFormRef = ref();

// 表单数据
let ruleForm = ref({
  cate_name: "",
  cate_alias: "",
});

// 表单检验规则
const rules = {
  cate_name: [
    {
      required: true,
      message: "请输入分类名称",
      trigger: "blur",
    },
    {
      pattern: /^\S{1,10}$/,
      message: "分类名必须是1-10位的非空字符",
      trigger: "blur",
    },
  ],
  cate_alias: [
    { required: true, message: "请输入分类别名", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9]{1,15}$/,
      message: "分类别名必须是1-15位的字母数字",
      trigger: "blur",
    },
  ],
};

/**
 * 打开弹窗
 * @param {Object} row  某一行的数据
 */
const open = (row) => {
  dialogVisible.value = true;
  console.log(row);

  // 回显数据
  ruleForm.value = { ...row };
};
// 暴露open方法
defineExpose({
  open,
});
/**
 * 提交
 */
const onSubmit = async () => {
  await ruleFormRef.value.validate();
  ruleForm.value.id
    ? await artEditChannelService(ruleForm.value)
    : await artAddChannelService(ruleForm.value);
  ElMessage({
    type: "success",
    message: ruleForm.value.id ? "编辑成功" : "添加成功",
  });
  dialogVisible.value = false;
  emit("success");
};

const emit = defineEmits(["success"]);
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    :title="ruleForm.id ? '编辑分类' : '添加分类'"
    width="30%"
  >
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px; padding: 20px 30px 10px 0"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="100"
    >
      <el-form-item label="分类名称" prop="cate_name">
        <el-input v-model="ruleForm.cate_name" />
      </el-form-item>
      <el-form-item label="分类别名" prop="cate_alias">
        <el-input v-model="ruleForm.cate_alias" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
